package net.mohas.docsearch.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.ContentHandler;

/**
 *
 * @author Muhammad, 14 April 2014
 * 
 */
public class TextOperation {
	
    private String lokasiberkas;
    private String teks;
    private Analyzer analyzer;

    public TextOperation(Analyzer analyzer) {
        this.analyzer = analyzer;
    }

    public Analyzer getAnalyzer() {
        return analyzer;
    }

    public void setAnalyzer(Analyzer analyzer) {
        this.analyzer = analyzer;
    }

    public String getLokasiberkas() {
        return lokasiberkas;
    }

    public void setLokasiberkas(String lokasiberkas) {
        this.lokasiberkas = lokasiberkas;
    }

    public String getDocumentText(String lokasiberkass) {
        
    	setLokasiberkas(lokasiberkass);
        
        try {
        	
        	InputStream input = new FileInputStream(new File(lokasiberkas));
        	ContentHandler textHandler = new BodyContentHandler(-1);
        	Metadata metadata = new Metadata();
        	ParseContext context = new ParseContext();
        	
        	AutoDetectParser parser = new AutoDetectParser();
        	parser.parse(input, textHandler, metadata, context);
        	input.close();
			
        	teks = textHandler.toString();

        } catch (Exception e) {
			e.printStackTrace();
		}

        return teks;
    }

    public void setTeks(String teks) {
        this.teks = teks;
    }

    public List<String> tokenize(Analyzer analyzerr, String tekss) {
        setAnalyzer(analyzerr);
        setTeks(tekss);
        List<String> result = new ArrayList<String>();
        TokenStream stream = analyzer.tokenStream("FIELDNAME", new StringReader(teks));
        try {
            while (stream.incrementToken()) {
                result.add(stream.getAttribute(CharTermAttribute.class).toString());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return result;
    }
}
